#include <fs/vfs.h>
#include <utils/string.h>
#include <mm/kmalloc.h>

#define TAR_BLOCK_SIZE 512

struct tar_header {
    char name[100];
    char mode[8];
    char uid[8];
    char gid[8];
    char size[12];
    char mtime[12];
    char chksum[8];
    char typeflag;
    char linkname[100];
    char magic[6];
    char version[2];
    char uname[32];
    char gname[32];
    char devmajor[8];
    char devminor[8];
    char prefix[155];
}

uint8 is_end_of_archive(uint8 *cursor) {
    int idx = 0;
    for (idx = 0; idx < 2 * TAR_BLOCK_SIZE; idx++) {
        if (cursor[idx] != 0) {
            return 0;
        }
    }
    return 1;
}

uint64 to_octal(uint8 *octalstring) {
    uint32 len = strlen(octalstring) - 1;
    uint64 octal = 0;
    uint32 exp = 1;
    for (;len >= 0; len--) {
        octal += (octalstring[len] - '0') * exp;
        exp *= 8;
    }
    return octal;
}

struct fs_node *fs_tar_create(uint8 *data) {
    kdebug("Starting reading tar file system\n");
    char *cursor = data;
    struct fs_node *root = kmalloc(sizeof(struct fs_node));
    root->dev_id = 0;
    root->file_id = 0;
    strcpy(root->name, "/");
    root->size = 0;
    root->seek_cursor = 0;
    root->mode = 0755;
    root->mtime = root->atime = root->ctime = 0;

    while (!is_end_of_archive(cursor)) {
        // read header
        struct tar_header header;
        memcpy(&header, cursor, sizeof(struct tar_header));
        cursor += TAR_BLOCK_SIZE;
        kprintf("Filename: %s\n", header.name);
        long content_size = to_octal(header.size);
        kprintf("Size: %d\n", content_size);
        int num_block = con
    }
}

/*
        printf("Filename: %s\n", header.name);
        long content_size = to_octal(header.size);
        printf("Size: %lu bytes\n", content_size);
        int num_blocks = content_size / 512;
        if (content_size % 512 != 0){
            num_blocks += 1;
        }
        printf("Num. Of Blocks: %d", num_blocks);
        // read content
        while(num_blocks--) {
            char block[513];
            printf("\n------ Block ------\n");
            memcpy(block, cursor, 512);
            block[512] = 0;
            cursor += 512;
        }
    }
    return 0;
}

*/

/* TODO: implement this */
int32 fs_tar_open(struct fs_node *node) {
    return 0;
}

int32 fs_tar_read(struct fs_node *node) {
    return 0;
}

int32 fs_tar_write(struct fs_node *node) {
    return 0;
}

int32 fs_tar_close(struct fs_node *node) {
    return 0;
}

int32 fs_tar_link(struct fs_node *node) {
    return 0;
}

int32 fs_tar_seek(struct fs_node *node) {
    return 0;
}

int32 fs_tar_unlink(struct fs_node *node) {
    return 0;
}
